import Core.Basic
from Core.package import *




class Worker_Thread(QThread):
    thread_task_data = Signal(dict)
    def __init__(self, parent = None):
        super().__init__(parent)
        self.driver = Core.Basic.GlobalVar.driver
        self.task_data = dict()
    
    def run(self):
        driver = Core.Basic.GlobalVar.driver
        # 定义变量,用来获取子线程采集的数据
        Title = str()
        Main_Images_Url = list()
        Main_Video_Url = list()
        Sku_List = list()
        Detail_Images_Url = list()
        Product_Parm_List = list()
        From_Website = "XiaoHongShu"
        Src_Product_Url = driver.current_url
        
        
        try:
            # 1.获取标题
            Title = ""

            # 2.获取主图
            main_images_xpath = [
                "//div[@class='img-container']/img"
            ]
            for xpath in main_images_xpath:
                try:
                    elements = driver.find_elements(by=By.XPATH, value=xpath)
                    for element in elements:
                        url = element.get_attribute("src").replace("_q50.jpg_.webp", "")
                        url = f"https:{url}" if url.startswith("//") else url
                        Main_Images_Url.append(url)

                    if Main_Images_Url:
                        print(f"提示 : 获取主图成功!获取到的主图数量为 : {len(Main_Images_Url)}")
                        break
                    
                except TimeoutException as e:
                    print(f"提示 : Xpath : {xpath} 获取主图元素失败!")
            
            # 3.获取主图视频
            Main_Video_Url = ""
            
            # 4.获取 SKU 列表
            Sku_List = list()
            
            # 5.获取商品详情
            Detail_Images_Url = Main_Images_Url
            
            # 6.获取商品描述
            Product_Parm_List = list()
            
            # 整合数据
            self.task_data = {
                "title": Title,
                "main_images_list": Main_Images_Url,
                "main_video_url": Main_Video_Url,
                "sku_list": Sku_List,
                "detail_images_url": Detail_Images_Url,
                "product_parm_list": Product_Parm_List,
                "from_website": From_Website,
                "src_product_url": Src_Product_Url
            }
  
        except Exception as e:
            print(f"提示 : 员工线程任务发生错误!\n\
                    错误信息: {e}")
        finally:
            self.thread_task_data.emit(self.task_data)
        
        
        
        # 线程任务完成，会自动发送信号的,无需手动发送,手动发送可能会导致发送两遍信号.
        # self.finished.emit()
    def __delattr__(self, name):
        print(f"提示 : 子任务子线程运行结束!正在销毁资源 {self}")
        return super().__delattr__(name)
    

class Staff_Get_Data_XiaoHongShu(QObject):
    Start_Task = Signal()   # 任务开始信号,启动任务时,请发送此信号
    Task_Finish = Signal()   # 任务完成信号,任务结束时候,请发送此信号
    Current_Completion_Process = Signal(int)
    Emergency_Stop = Signal()  # 紧急停止信号
    OnlyRun = Signal()  # 仅运行信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Start_Task.connect(self.RunTask)
        
    @Slot(str)
    def slot_fun(self,text):
        print(f"我是槽函数,我是 {text}")

    # 设置员工属性
    def Set_Staff_Attribute(self,**kwargs):
        """设置员工对象的属性，用于后续任务执行
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        print(f"已设置属性: {kwargs.keys()}")

    def RunTask(self):

        # 获取需要操作的 主线程 窗口的 UI 对象
        # 使用 self.parent() 获取父对象
        self.parent_widget = self.parent()
        if self.parent_widget is None:
            print(f"提示 : 父对象为空!\n请将创建员工对象时,将父对象作为参数传入!")
            return
        # 获取 任务按钮 UI 控件对象
        self.task_button_object_name = "pushButton_get_data_xiaohongshu"
        self.task_button : QPushButton = self.parent().findChild(QPushButton,self.task_button_object_name)
        if self.task_button is None:
            print(f"提示 : 程序无法找到 {self.task_button_object_name} 对应的按钮!")
            print(f"提示 : 子任务结束!")
            return
        self.textedit_get_datas_object_name = "textEdit_get_datas"
        self.textedit_get_datas : QTextEdit = self.parent().findChild(QTextEdit,self.textedit_get_datas_object_name)
        if self.textedit_get_datas is None:
            print(f"提示 : 程序无法找到 {self.textedit_get_datas_object_name} 对应的文本框!")
            print(f"提示 : 子任务结束!")
            return



        # 创建子线程
        self.workerthread = Worker_Thread()



        # 绑定信号
        self.workerthread.finished.connect(lambda : QMessageBox.information(self.parent_widget,"提示","采集 [小红书笔记] 任务完成!"))
        self.workerthread.finished.connect(lambda : self.Task_Finish.emit())    # 子线程运行结束代表该员工类的任务结束
        self.workerthread.finished.connect(lambda : self.workerthread.quit())   # 线程结束，销毁线程
        self.workerthread.finished.connect(lambda : self.deleteLater())
        self.workerthread.finished.connect(lambda : self.task_button.setEnabled(True))
        self.workerthread.thread_task_data.connect(lambda task_data: self.textedit_get_datas.setText(json.dumps(task_data,ensure_ascii=False,indent=4)))


        # 启动子线程,开始执行任务
        self.task_button.setEnabled(False)
        self.workerthread.start()
        

        


















if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    # 编写 控制台 程序
    staff = Staff_Get_Data_XiaoHongShu(app)
    staff.RunTask()
    
    sys.exit(app.exec_())